package com.fgs.common;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.fgs.common.other.CommonEvent;
import com.fgs.common.utils.ToastUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxFragment;
import com.xuexiang.xutil.system.KeyboardUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.ObservableTransformer;
/**
 * @author fgs
 * @date 2020/3/27
 **/

/**
 * 父类->基类->动态指定类型->泛型设计（通过泛型指定动态类型->由子类指定，父类只需要规定范围即可）
 */

public abstract class CommonFragment<V extends CommonView, P extends CommonPresenter<V>> extends RxFragment implements CommonView {
    private V mView;
    private P mPresenter;
    public View winView ;
    private Unbinder mUnbinder;

    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;
    private boolean isPrepared;
    /**
     * 是否已经加载数据
     */
    private boolean isHasLoadData;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPrepare();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                initPrepare();
            } else {
                onUserVisible();
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false;
            } else {
                onUserInvisible();
            }
        }
    }

    private synchronized void initPrepare() {

        if (isPrepared) {
            onFirstUserVisible();
        } else {
            isPrepared = true;
        }
    }

    /**
     * fragment 第一次可见，可进行初始化数据操作
     */

    protected void onFirstUserVisible() {
        onUserVisible();
    }

    /**
     * 当前fragment处于用户可见状态 ，可进行数据请求
     */

    protected void onUserVisible() {
        if (getActivity() == null) {
            return;
        }
        if (!isHasLoadData) {
            init();
            isHasLoadData = true;
        }

    }


    protected boolean isHasLoadData() {
        return isHasLoadData;
    }

    /**
     * 当前fragment处于用户不可见状态
     */
    protected void onUserInvisible() {

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        winView =view;
        mUnbinder = ButterKnife.bind(this, view);
        if (null == mPresenter) {
            mPresenter = createPresenter();
        }

        if (null == mView) {
            mView = createView();
        }

        if (null != mPresenter && null != mView) {
            mPresenter.attachView(mView);
        }

        return view;
    }

    protected abstract int getLayoutId();

    protected abstract V createView();

    protected abstract P createPresenter();

    protected abstract void init();


    public P getPresenter() {
        return mPresenter;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();

        //是否需要懒加载
        if (isNeedLazyLoad()) {
            if (isFirstResume) {
                isFirstResume = false;
                return;
            }
            if (getUserVisibleHint()) {
                onUserVisible();
            }
        } else {
            onUserVisible();
        }


    }

    /**
     * 设置是否需要懒加载
     * 默认需要
     */
    protected boolean isNeedLazyLoad() {
        return true;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()) {
            onUserInvisible();
        }
    }

    @Subscribe
    public void onEvent(CommonEvent event) {

    }

    public void openActivity(Class<?> pClass) {
        Intent intent = new Intent(getContext(), pClass);
        startActivity(intent);
    }

    public void openActivity(Class<?> pClass, Bundle bundle) {
        Intent intent = new Intent(getContext(), pClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    protected void hideKeyboard() {

        try {
            KeyboardUtils.hideSoftInput(getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setMsg(String msg) {
        ToastUtil.showShortToast(msg);
    }

    @Override
    public <T> ObservableTransformer<T, T> bindLifecycle() {
        return this.bindUntilEvent(FragmentEvent.ATTACH);
    }

    public void showToast(String message) {
        ToastUtil.showShortToast(message);
    }

    public void showToast(int stringId) {
        ToastUtil.showShortToast(stringId);
    }

    public boolean onBackPressed() {
        return false;
    }
}